package boot.spring.controller;

import boot.spring.model.request.CreateTableRequest;
import boot.spring.model.response.Response;
import boot.spring.service.DorisTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/table")
public class DorisTableController {
    @Autowired
    private DorisTableService tableService;

    @PostMapping("/create")
    public Response<String> create(@RequestBody CreateTableRequest request) {
        try {
            tableService.createTable(request.getSchema(),
                    request.getNewTable(), request.getTemplateTable(),
                    request.isIfNotExists());
            return Response.success("success");
        } catch (Exception e) {
            return Response.fail("Failed: " + e.getMessage());
        }
    }

    /**
     * 清空指定数据库的表名缓存
     *
     * @param schema 数据库名称（可选）
     * @return 操作结果
     */
    @PostMapping("/clear")
    public Response<String> clearCache(
            @RequestParam(required = false) String schema) {
        if (schema != null && !schema.isEmpty()) {
            tableService.clearCache(schema);
            return Response.success("Cleared cache for schema: " + schema);
        } else {
            tableService.clearAllCache();
            return Response.success("Cleared all table caches");
        }
    }
}
